package com.example.security.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.security.constant.AuthConstant;
import com.example.security.service.UserInfoService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @application:
 * @author: LiYuhang
 * @Date: 2021/5/29 21:25
 * @version: 0.1
 * @Description :
 * @Modified By:
 */
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {

     private static final Logger log = LoggerFactory.getLogger(TokenAuthenticationFilter.class);

    @Autowired
    RedisTemplate<String, String> redisTemplate;


    @Override
    protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain) throws ServletException, IOException {

        String authHeader = request.getHeader(AuthConstant.tokenHeader);
        if (authHeader != null && authHeader.startsWith(AuthConstant.tokenHead)) {
            final String authToken = authHeader.substring(AuthConstant.tokenHead.length());
            if (authToken != null && redisTemplate.hasKey(authToken)) {
                String userJson = redisTemplate.opsForValue().get(authToken);
                if (StringUtils.isNotBlank(userJson)  && SecurityContextHolder.getContext().getAuthentication() == null) {
                    UserDetails userDetails = JSON.parseObject(userJson,UserDetails.class);
                    //可以校验token和username是否有效，目前由于token对应username存在redis，都以默认都是有效的
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                            request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}
